"use client";
import { useState, useMemo } from "react";
import { CategoryItem } from "../types/video";
import { useEffect } from "react";

export interface SearchBarProps {
  keyword?: string;
  category?: CategoryItem;
  onChange: (next: { keyword: string; category: number }) => void;
}

export default function SearchBar({
  keyword = "",
  category,
  onChange,
}: SearchBarProps) {
  const [kw, setKw] = useState(keyword);
  const [cat, setCat] = useState<number>(0);
  const [categories, setCategorys] = useState<CategoryItem[]>([]);
  useEffect(() => {
    fetch(`/api/categories`)
      .then((res) => res.json())
      .then((data) => {
        setCategorys([{ name: "全部", id: 0, coverUrl: "" }].concat(data.data));
      });
  }, []);

  useEffect(() => {
    // eslint-disable-next-line react-hooks/set-state-in-effect
    setCat(category?.id || 0);
  }, [category]);

  const canSearch = useMemo(() => kw.trim().length > 0 || (cat && !category), [kw, cat, category]);

  return (
    <div className="mb-5 flex flex-col gap-3 sm:flex-row sm:items-center">
      <input
        value={kw}
        onChange={(e) => setKw(e.target.value)}
        placeholder="搜索视频..."
        className="h-10 w-full rounded-md border border-zinc-300 bg-white px-3 text-sm outline-none focus:border-zinc-500 dark:border-zinc-700 dark:bg-zinc-950"
      />
      {!category && (
        <select
          value={cat}
          onChange={(e) => setCat(Number(e.target.value || 0))}
          className="h-10 rounded-md border border-zinc-300 bg-white px-3 text-sm outline-none focus:border-zinc-500 dark:border-zinc-700 dark:bg-zinc-950"
        >
          {categories.map((c) => (
            <option key={c.id} value={c.id}>
              {c.name}
            </option>
          ))}
        </select>
      )}
      <button
        onClick={() => onChange({ keyword: kw, category: cat })}
        disabled={!canSearch}
        className="h-10 rounded-md bg-zinc-900 px-4 text-sm text-white disabled:cursor-not-allowed disabled:opacity-60 dark:bg-zinc-100 dark:text-black"
      >
        搜索
      </button>
      {canSearch ? (
        <button
          onClick={() => {
            setKw("");
            setCat(0);
            onChange({ keyword: "", category: category?.id || 0 });
          }}
          className="h-10 rounded-md border border-zinc-300 px-4 text-sm dark:border-zinc-700"
        >
          重置
        </button>
      ) : null}
    </div>
  );
}
